package com.nj.liandi.gulimall.product.service.impl;

import com.nj.liandi.gulimall.product.service.CategoryBrandRelationService;
import com.nj.liandi.gulimall.product.vo.BrandVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nj.liandi.common.utils.PageUtils;
import com.nj.liandi.common.utils.Query;

import com.nj.liandi.gulimall.product.dao.BrandDao;
import com.nj.liandi.gulimall.product.entity.BrandEntity;
import com.nj.liandi.gulimall.product.service.BrandService;
import org.springframework.transaction.annotation.Transactional;


@Service("brandService")
public class BrandServiceImpl extends ServiceImpl<BrandDao, BrandEntity> implements BrandService {

    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String key = (String) params.get("key");
        QueryWrapper<BrandEntity> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(key)) {
            wrapper.eq("brand_id",key).or().like("name",key);
        }
        IPage<BrandEntity> page = this.page(
                new Query<BrandEntity>().getPage(params),wrapper
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void updateDetail(BrandEntity brand) {

        this.updateById(brand);

        if (StringUtils.isNotEmpty(brand.getName())) {
            categoryBrandRelationService.updateBrand(brand.getBrandId(),brand.getName());
        }
        //更新关联其他
    }

    @Override
    public List<BrandVo> getBrandsById(List<Long> brandIds) {

        List<BrandEntity> brandEntities = baseMapper.selectList(new QueryWrapper<BrandEntity>().in("brand_id", brandIds));
        List<BrandVo> collect =null;
        if (brandEntities!=null&&brandEntities.size()>0) {
             collect = brandEntities.stream().map(item -> {
                BrandVo brandVo = new BrandVo();
                brandVo.setBrandId(item.getBrandId());
                brandVo.setBrandName(item.getName());
                return brandVo;
            }).collect(Collectors.toList());
        }
        return collect;
    }

}